import axios from "axios";
import React, { useEffect, useState } from "react";
import { Search, Space, Tag } from "react-vant";
import { ListState } from "../../hooks/useFetchList";
import { matchReplaceString } from "../../utils/matchReplaceString";
import { useNavigate } from "react-router-dom";
const Index: React.FC = () => {
  const navigate = useNavigate()
  // 搜索记录
  const [list, setList] = useState<string[]>(
    JSON.parse(localStorage.getItem("list") || "[]")
  );
  // 建议搜索列表
  const [adList, setAdList] = useState<ListState[]>([]);
  // 存储搜索的内容
  const [value, setValue] = useState("");
  // 状态
  const [isAdviceSearch, setIsAdViceSearch] = useState(false);

  // 确定搜索
  const handleSearch = (value: string) => {
    // 1. 新增历史记录 并且 去除重复
    const arr = [...new Set([value, ...list])];
    setList(arr);
  };
  // 实时输入
  const handleChange = async (value: string) => {
    setValue(value);
    // 切换状态
    setIsAdViceSearch(value !== "");
    if (value === "") {
      return;
    }
    const resp = await axios.get("/api/lists", { params: { value } });
    setAdList(resp.data.data);
  };
  // 清空历史几率
  const clearList = () => {
    setList([]);
  };
  // 删除数据
  const deleteListByIndex = (v: string, i: number) => {
    // 方式一：
    // const newList = [...list];
    // newList.splice(i, 1);
    // setList(newList)
    // 方式二：
    setList(list.filter((item) => item !== v));
    // 方式三：
    // 其他方案
  };

  // 利用副作用函数 进行 本地存储
  useEffect(() => {
    localStorage.setItem("list", JSON.stringify(list));
  }, [list]);

  return (
    <div>
      <Search
        placeholder="请搜索内容"
        onSearch={(value) => handleSearch(value)}
        onChange={(value) => handleChange(value)}
      ></Search>
      <div style={{ padding: 10 }}>
        {!isAdviceSearch ? (
          <div>
            <h3 style={{ display: "flex", justifyContent: "space-between" }}>
              <span>历史记录</span>
              <span onClick={() => clearList()}>X</span>
            </h3>
            <Space>
              {list.map((v, i) => {
                return (
                  <Tag
                    key={i}
                    closeable
                    onClose={() => deleteListByIndex(v, i)}
                  >
                    {v}
                  </Tag>
                );
              })}
            </Space>
          </div>
        ) : (
          <div className="ad-list">
            <ul>
              {adList.map((v) => {
                return (
                  <li
                    onClick={() => navigate('/detail/' + v.id)}
                    key={v.id}
                    dangerouslySetInnerHTML={{
                      __html: matchReplaceString(value, `${v.title}-${v.desc}`),
                    }}
                  ></li>
                );
              })}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
};

export default Index;
